package com.t.codebook.controller;

import com.github.pagehelper.PageInfo;
import com.t.codebook.annotation.AuthCheck;
import com.t.codebook.common.BaseResponse;
import com.t.codebook.common.DeleteRequest;
import com.t.codebook.common.ErrorCode;
import com.t.codebook.common.ResultUtils;
import com.t.codebook.constant.UserConstant;
import com.t.codebook.exception.BusinessException;
import com.t.codebook.exception.ThrowUtils;
import com.t.codebook.model.dto.code.CodeAddRequest;
import com.t.codebook.model.dto.code.CodeEditRequest;
import com.t.codebook.model.dto.code.CodeQueryRequest;
import com.t.codebook.model.dto.code.CodeUpdateRequest;
import com.t.codebook.model.entity.Code;
import com.t.codebook.model.entity.User;
import com.t.codebook.model.vo.CodeVO;
import com.t.codebook.service.CodeService;
import com.t.codebook.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * 代码库接口
 *
 */
@RestController
@RequestMapping("/code")
@Slf4j
public class CodeController {

    @Resource
    private CodeService codeService;

    @Resource
    private UserService userService;

    /**
     * 创建代码库
     *
     * @param codeAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addCode(@RequestBody CodeAddRequest codeAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(codeAddRequest == null, ErrorCode.PARAMS_ERROR);
        Code code = new Code();
        BeanUtils.copyProperties(codeAddRequest, code);
        // 写入数据库
        boolean result = codeService.save(code);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回新写入的数据 id
        long newCodeId = code.getId();
        return ResultUtils.success(newCodeId);
    }

    /**
     * 删除代码库
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteCode(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Code oldCode = codeService.getById(id);
        ThrowUtils.throwIf(oldCode == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldCode.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = codeService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 更新代码库（仅管理员可用）
     *
     * @param codeUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateCode(@Valid @RequestBody CodeUpdateRequest codeUpdateRequest) {
        if (codeUpdateRequest == null || codeUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Code code = new Code();
        BeanUtils.copyProperties(codeUpdateRequest, code);
        // 判断是否存在
        long id = codeUpdateRequest.getId();
        ThrowUtils.throwIf(codeService.getCodeVO(id) == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = codeService.updateById(code);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }


    /**
     * 编辑代码库（给用户使用）
     *
     * @param codeEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editCode(@Valid @RequestBody CodeEditRequest codeEditRequest, HttpServletRequest request) {
        if (codeEditRequest == null || codeEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        Code code = new Code();
        BeanUtils.copyProperties(codeEditRequest, code);
        User loginUser = userService.getLoginUser(request);
        // 判断是否存在
        long id = codeEditRequest.getId();
        Code oldCode = codeService.getById(id);
        ThrowUtils.throwIf(oldCode == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldCode.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = codeService.updateById(code);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }



    /**
     * 根据 id 获取代码库（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<CodeVO> getCodeVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Code code = codeService.getById(id);
        ThrowUtils.throwIf(code == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(codeService.getCodeVO(id));
    }





    /**
     * 分页获取代码库列表（仅管理员可用）
     *
     * @param codeQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<PageInfo<CodeVO>> listCodeByPage(@RequestBody CodeQueryRequest codeQueryRequest) {
        return ResultUtils.success(codeService.getCodeVOPage(codeQueryRequest));
    }



    /**
     * 分页获取当前登录用户创建的代码库列表
     *
     * @param codeQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<PageInfo<CodeVO>> listMyCodeVOByPage(@RequestBody CodeQueryRequest codeQueryRequest,HttpServletRequest request) {
        ThrowUtils.throwIf(codeQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        User loginUser = userService.getLoginUser(request);
        codeQueryRequest.setUserId(loginUser.getId());
        long size = codeQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        PageInfo<CodeVO> codePage = codeService.getCodeVOPage( codeQueryRequest);
        // 获取封装类
        return ResultUtils.success(codePage);
    }


}
